import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2022-10-25
 * Time: 10:32
 */
public class Test {
    /**
     * 堆排序
     * 时间复杂度 O(n*logn)
     * 空间复杂度O(1)
     *稳定性：不稳定
     * @param array
     */
    public static void heapSort(int[] array) {
        createrBigHeap(array);
        int end = array.length-1;
        while (end > 0){
            swap(array,0,end);
            shifDown(array,0,end);
            end--;
        }
    }

    private static void createrBigHeap(int[] array) {
        for (int parent = (array.length - 1 - 1) / 2; parent >= 0; parent--) {
            shifDown(array, parent, array.length);
        }
    }

    private static void shifDown(int[] array, int parent, int len) {
        int child = 2 * parent + 1;
        while (child < len) {
            if (child + 1 < len && array[child + 1] > array[child]) {
                child++;
            }
            if (array[parent]  < array[child]) {
                swap(array, parent, child);
                parent = child;
                child = 2 * parent + 1;
            }else {
                break;
            }
        }
    }

    private static void swap(int[] array, int parent, int child) {
        int tmp = array[parent];
        array[parent] = array[child];
        array[child] = tmp;
    }

    public static void main(String[] args) {
        int[] array = {3, 5, 2, 6, 7, 4, 8, 10};
        heapSort(array);
        System.out.println(Arrays.toString(array));
    }
}
